package com.example.flowerpcback.services;

import com.example.flowerpcback.dto.Enterprise;
import com.example.flowerpcback.dto.EnterpriseExample;
import com.example.flowerpcback.dto.Roles;
import com.example.flowerpcback.dto.RolesExample;
import com.example.flowerpcback.mapper.EnterpriseMapper;
import com.example.flowerpcback.mapper.RolesMapper;
import com.example.flowerpcback.req.EnterpriseReq;
import com.example.flowerpcback.req.RolesReq;
import com.example.flowerpcback.resp.EnterpriseResp;
import com.example.flowerpcback.resp.PageResp;
import com.example.flowerpcback.resp.RolesResp;
import com.example.flowerpcback.utils.CopyUtil;
import com.example.flowerpcback.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class EnterpriseService {
    private static final Logger LOG = LoggerFactory.getLogger(EnterpriseService.class);

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private SnowFlake snowFlake;

    public Enterprise save(EnterpriseReq req){

        Enterprise enterprise = new CopyUtil().copy(req, Enterprise.class);
        if(req.getId() == null){
            Long id = snowFlake.nextId();
            req.setId(id);
            enterpriseMapper.insert(enterprise);
        }else {
            enterpriseMapper.updateByPrimaryKey(enterprise);
        }

        return enterprise;

    }

    public PageResp<EnterpriseResp> list(EnterpriseReq req) {
        EnterpriseExample enterpriseExample = new EnterpriseExample();
        EnterpriseExample.Criteria criteria = enterpriseExample.createCriteria();
        if(req.getName() != null) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if(req.getType() != null) {
            criteria.andTypeEqualTo(req.getType());
        }

        PageHelper.startPage(req.getPage(),req.getSize());
        List<Enterprise> enterpriseList = enterpriseMapper.selectByExample(enterpriseExample);

        PageInfo<Enterprise> pageInfo = new PageInfo<>(enterpriseList);
        PageResp<EnterpriseResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());

        List<EnterpriseResp> res = new CopyUtil().copyList(enterpriseList,EnterpriseResp.class);

        pageResp.setList(res);
        return pageResp;
    }

    public void delete(EnterpriseReq req){
        enterpriseMapper.deleteByPrimaryKey(req.getId());
    }

}
